import { Component, OnInit, ViewChild, Input, Output, EventEmitter } from '@angular/core';
import { DxTreeViewComponent, DxTreeListComponent, DxScrollViewComponent } from 'devextreme-angular';
import { RestUtil as Rest} from '../../restUtil';
import { UniConfigService } from '../../../config/uni-config.service';

@Component({
  selector: 'app-transform-grid',
  templateUrl: './transform-grid.component.html',
  styleUrls: ['./transform-grid.component.css'],
  providers:[Rest,UniConfigService]
})
export class TransformGridComponent implements OnInit {
  @ViewChild('leftTree') leftTree: DxTreeListComponent;
  @ViewChild('rightTree') rightTree: DxTreeListComponent;
  // @Input() leftSource: any[] = [{"expanded":false,"level":1,"Id":2020031621139638,"text":"包1","parentId":0},{"parentId":2020031621139638,"expanded":false,"level":2,"Id":2020031621139642,"text":"包2"},{"expanded":false,"level":2,"Id":2020031621139646,"text":"包3"},{"expanded":false,"level":2,"Id":2020031621139650,"text":"包4"},{"expanded":false,"level":2,"Id":2020031621139654,"text":"包5"},{"expanded":false,"level":2,"Id":2020031621139658,"text":"包6"},{"expanded":false,"level":2,"Id":2020031621139662,"text":"包7"},{"expanded":false,"level":2,"Id":2020031621139666,"text":"包8"},{"expanded":false,"level":2,"Id":2020031621139670,"text":"包9"},{"expanded":false,"level":2,"Id":2020031621139674,"text":"包10"}];
  @Input() leftSource: any[] = [];
  @Input() rightSource: any[] = [];
  @Input() leftWidth = '200px';
  @Input() rightWidth = '200px';

  @Output() onAdd: EventEmitter<any> = new EventEmitter();
  @Output() onRemove: EventEmitter<any> = new EventEmitter();
  
  // 左侧选中的
  keys: any = [];
  // 右侧数据的ids集
  rkeys: any = [];

  constructor(
    private rest : Rest,
    private conf : UniConfigService
  ) { }

  ngOnInit() {

    // right 
    // console.log('transform.left = ',this.rightSource);
    this.rightSource && this.rightSource.forEach(ele => {
      ele.parentId != 0 && this.keys.push(ele.Id);
      this.rkeys.push(ele.Id);
    });
  }


  // 新增按钮
  add(){
    const left = this.leftTree.instance.getSelectedRowsData();
    // console.log('selectLeftData = ', left);

    // 父节点集
    let pIds = [] ;
    // 子节点集合
    let sub = [];
    (left && left.length > 0 ) && left.forEach(val=>{
      // 叶子节点 && 不在pIds集里
      if(val.parentId != 0 && !pIds.includes(val.parentId)){
        pIds.push(val.parentId);
        let pnode = this.leftSource.filter(vval=>{
          return (vval.Id == val.parentId);
        });
        left.findIndex(v=>v.Id == pnode[0].Id) == -1 && left.push(...pnode);
        // console.log('[] = ',pnode,left);
      }
      // 是父节点
      if(val.parentId == 0){
        // 循环加载它所有的子节点
        var tmpSub = this.leftSource.filter(vval=>{
          // 检测left集是否包含当前节点
          var hasIdx = left.findIndex(vv=>vval.Id == vv.Id);
          return (vval.parentId == val.Id && hasIdx == -1);
        });
        sub.push( ... tmpSub );
      }
    });
    if(sub.length > 0 ){
      left.push( ...sub );
    }

    //重置变量
    sub = [];
    if(left.length > 0){
      // console.log(left)
      let ret = [];
      left.map(val=>{
        ret.push(Object.assign({},val));
        val.parentId != 0 && sub.push(val);
        !this.rkeys.includes(val.Id) && this.rkeys.push(val.Id);
      });
      // console.log('after add(). this.rkeys = ',this.rkeys);

      this.rightSource = ret;
      this.rightTree.instance.deselectAll();

      // 向上传递的数据应该是叶子节点, 不包括父节点的数据集
      this.onAdd.emit(ret);
    }
  }

  // 删除按钮
  remove(){
    // this.keys = [];
    const right = this.rightTree.instance.getSelectedRowsData();
    if(right.length > 0){

      // console.log('selected.before = ',right);
      // console.log('keys.before = ',this.keys,this.rkeys);
      let lkeys = [],sub = [] ;
      // 方案2. 循环right, 选中的节点
      right.map(ele=>{
        //叶子节点
        if(ele.parentId != 0 ){
          //从右侧ids集中删除, 选中的id;
          let ridx = this.rkeys.findIndex(v=>v == ele.Id);
          //存在
          if(ridx > -1){
            this.rkeys.splice(ridx,1);
          }
        }
        //Is parent node
        else {
          // 从右侧集合中筛出其下的所有子节点, 执行删除操作,从rkeys中
          this.rightSource.map(rsNode=>{
            //找出叶子节点
            let isSub = rsNode.parentId == ele.Id;
            let inarr = this.rkeys.findIndex(v=>v == rsNode.Id);
            if(isSub && inarr > -1){
              this.rkeys.splice(inarr,1);
            }
          });
          //删除父节点
          let pidx = this.rkeys.findIndex(v=>v == ele.Id);
          pidx > -1 && this.rkeys.splice(pidx,1);
        }
      });
      // console.log('keys.deleting = ',this.rkeys);


      //rkeys是反向集合, left的keys(选中)集,得取反
      //组织left的keys集合
      this.rightSource.map(ele=>{
        let inarr = this.rkeys.includes(ele.Id);
        // 反向收集
        // 不在右Ids集 && 是叶子节点 
        inarr && ele.parentId != 0 && lkeys.push( ele.Id ); 
      });
      // 赋回左侧Ids集
      this.keys = lkeys ;
      // console.log('selected.after = ',right);
      // console.log('keys.after = ',this.keys,lkeys,this.rkeys);
      // console.log('rightSource = ',this.rightSource);
      // 重置左侧选中的keys
      this.leftTree.instance.selectRows(this.keys,false);


      // 用于返回, 目的是封装割断引用的对象集
      let ret = [] ; 
      // 父节点
      let pIds = [] ;
      
      //修复父节点缺失的右侧集
      this.leftSource.forEach(val=>{
        // 收集在keys集中的数据
        var idx = this.keys.findIndex(v=>v==val.Id);
        idx > -1 && ret.push(Object.assign({},val)) ;
        
        //收集父节点
        let pId = val.parentId;
        idx > -1 && !pIds.includes(pId) && pIds.push(pId);
      });
      pIds.length > 0 && pIds.map(val=>{
        let pnode = this.leftSource.filter(v=>v.Id == val);
        pnode.length > 0 && (ret.push(...pnode));
      });
      // console.log('pIds = ',pIds,ret);

      // 将结果重新赋于右侧集
      this.rightSource = ret; 
      this.rightTree.instance.deselectAll();
      // console.log('ret = ',ret);

      //向上传递
      // {removed:[], right:[]}
      this.onRemove.emit({
        "removed":right,
        "right":ret
      });
    }
  }

}
